package cn.bone.auth.security.service.impl;

import cn.bone.auth.security.base.exception.MyUserNotFindException;
import cn.bone.auth.security.bean.SysRole;
import cn.bone.auth.security.bean.SysUser;
import cn.bone.auth.security.mapper.SysRoleMapper;
import cn.bone.auth.security.mapper.SysUserMapper;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser sysUser = sysUserMapper.selectByUserName(username);

        //用户不存在,抛出自定义的异常
        if(sysUser==null){
            throw new MyUserNotFindException("用户不存在");
        }

        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        List<SysRole> roles = sysRoleMapper.listByUsername(username);
        for(SysRole role : roles){
            authorities.add(new SimpleGrantedAuthority(role.getRoleTag()));
            System.out.println("role-tag: " + role.getRoleTag());
        }

        UserDetails userDetails = new User(
                sysUser.getUsername(),
                sysUser.getPassword(),
                sysUser.getUsable()==1,
                true,
                true,
                true,
                authorities);

        return userDetails;
    }
}
